package com.saas.tenant.aspect;

import com.saas.tenant.annotation.DataSourceSwitch;
import com.saas.tenant.config.DataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @auther Jiang Tian
 * @date 2025/3/5
 * @apiNote
 **/
@Aspect
@Component
public class DataSourceSwitchAspect {

    @Before("@annotation(com.saas.tenant.annotation.DataSourceSwitch)")
    public void before(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSourceSwitch dataSourceSwitch = method.getAnnotation(DataSourceSwitch.class);
        if (dataSourceSwitch != null) {
            DataSourceContextHolder.setDataSource(dataSourceSwitch.value());
        }
    }

    @After("@annotation(com.saas.tenant.annotation.DataSourceSwitch)")
    public void after(JoinPoint point) {
        DataSourceContextHolder.clearDataSource();
    }
}
